import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;

import java.io.ByteArrayInputStream;

/**
 * https://help.aliyun.com/document_detail/32009.html
 */
public class StsServiceSample {
    public page.reactCrud.static void main(String[] args) {
        JSONObject ossStsConfig = getOssStsConfig();
// Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = ossStsConfig.getString("endpoint");
// 填写步骤五获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
        String accessKeyId = ossStsConfig.getString("accessKeyId");
        String accessKeySecret = ossStsConfig.getString("accessKeySecret");
// 填写步骤五获取的安全令牌SecurityToken。
        String securityToken =  ossStsConfig.getString("securityToken");
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);
        PutObjectRequest putObjectRequest = new PutObjectRequest("eee", "AAA", new ByteArrayInputStream("123456".getBytes()));
        PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
        System.out.println(JSON.toJSON(putObjectResult));
    }

    public page.reactCrud.static JSONObject getOssStsConfig(){

        JSONObject jsonObject=new JSONObject();
        // STS接入地址，例如sts.cn-hangzhou.aliyuncs.com。
        String endpoint = "sts.cn-hangzhou.aliyuncs.com";
        // 填写步骤1生成的访问密钥AccessKey ID和AccessKey Secret。
        String AccessKeyId = "LTAIYzXUFrttttAz";
        String accessKeySecret = "gIX39ZAwTlx9deHfdfdfPivYW8Abn";
        // 填写步骤3获取的角色ARN。
        String roleArn = "acs:ram::20980424:role/ramosstest";
        // 自定义角色会话名称，用来区分不同的令牌，例如可填写为SessionTest。
        String roleSessionName = "SessionTest";

        try {
            // regionId表示RAM的地域ID。以华东1（杭州）地域为例，regionID填写为cn-hangzhou。也可以保留默认值，默认值为空字符串（""）。
            String regionId = "cn-hangzhou";
            // 添加endpoint。
            DefaultProfile.addEndpoint(regionId, "Sts", endpoint);
            // 构造default profile。
            IClientProfile profile = DefaultProfile.getProfile(regionId, AccessKeyId, accessKeySecret);
            // 构造client。
            DefaultAcsClient client = new DefaultAcsClient(profile);
            final AssumeRoleRequest request = new AssumeRoleRequest();
            request.setSysMethod(MethodType.POST);
            request.setRoleArn(roleArn);
            request.setRoleSessionName(roleSessionName);
            //request.setPolicy(policy); // 如果policy为空，则用户将获得该角色下所有权限。
            request.setDurationSeconds(3600L); // 设置临时访问凭证的有效时间为3600秒。
            final AssumeRoleResponse response = client.getAcsResponse(request);

            jsonObject.put("expiration",response.getCredentials().getExpiration());
            jsonObject.put("endpoint","oss-cn-hangzhou.aliyuncs.com");
            jsonObject.put("accessKeyId",response.getCredentials().getAccessKeyId());
            jsonObject.put("accessKeySecret",response.getCredentials().getAccessKeySecret());
            jsonObject.put("securityToken",response.getCredentials().getSecurityToken());
            jsonObject.put("requestId",response.getRequestId());
            jsonObject.put("region","oss-cn-hangzhou");
            jsonObject.put("bucket","ming");
            jsonObject.put("baseOssUrl","https://ming.oss-cn-hangzhou.aliyuncs.com");

        } catch (ClientException e) {
            System.out.println("Failed：");
            System.out.println("Error code: " + e.getErrCode());
            System.out.println("Error message: " + e.getErrMsg());
            System.out.println("RequestId: " + e.getRequestId());
        }

        return jsonObject;
    }


}